package com.cn.lf.wx.dacs.bussiness.author.utils;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.lf.wx.dacs.bussiness.author.serviceImpl.HisServiceImpl;
import com.cn.ym.log.Log;

@Component
public class Main {
	
	@Autowired
	private  HisServiceImpl hisServiceImpl;
	
	public static Main mainUtils;

//    public  List<String> METHOD_NAMES = Arrays.asList("medicalRecordFirstPage","admissionDischargeInfo", "admissionRecord",  "diseaseCourse", "deathRecord", "dischargeDiagnosisInfo", "dischargeRecord", "fistDiseaseCourse", "hospitalizationCost", "hospitalizationCostDetail", "hospitalizationOrderMedicine", "imageologyExam", "laboratoryTest", "laboratoryTestDetail", "medicalRecordFirstPage", "operationRecord", "transferInfo", "24hoursAdmissionDischargeInfo","pathologyInfo","readmissionRecord");
//    public  List<String> METHOD_VIEWS = Arrays.asList("v_etzl_medicalRecordFirstPage","v_etzl_admissionDischargeInfo", "v_etzl_admissionRecord", "v_etzl_diseaseCourse", "v_etzl_deathRecord", "v_etzl_dischargeDiagnosisInfo", "v_etzl_dischargeRecord", "v_etzl_fistDiseaseCourse", "v_etzl_hospitalizationCost", "v_etzl_hospitalizationCostDet", "v_etzl_hospitalizationOrderMed", "v_etzl_imageologyExam", "v_etzl_laboratoryTest", "v_etzl_laboratoryTestDetail", "v_etzl_medicalRecordFirstPage", "v_etzl_operationRecord", "v_etzl_transferInfo", "V_etzl_24hadmissiondischarge","v_etzl_pathologyInfo","v_etzl_readmissionRecord");
    public  List<String> METHOD_NAMES = Arrays.asList("admissionRecord");
    public  List<String> METHOD_VIEWS = Arrays.asList("v_etzl_admissionRecord");
    private  String DEFAULT_URL = "http://172.31.129.35:8080/open.api";

    private  Map<String, String> institutionInfo = new HashMap<String, String>(){
        {
            put("ncAppid", "1033035");      //请填写贵院的APP_ID
            put("ncAppSecret", "f5ce030982d1c74a1793173b73e11dee");   //请填写贵院的APP_SECRET
            put("ncVersion", "2.0.5");   //接口版本号
            put("ncHistory", "1");       //是否为历史数据
            put("ncCancel", "0");        //是否取消，0表示正常上传，1表示取消(删除)当前批次的数据
            put("ncBranchID", "0");     //分支ID，本部：0，分院1：1，分院2：2·
        }
    };

    public String upload(String ncMethod,Map<String,Object> map) throws FileNotFoundException, UnsupportedEncodingException {
    	String ncData="";
    	String datas = "";
    	//获取ncData
    	if("1".equals(map.get("type"))) {
    		//获取全部列表
    		String startTime = map.get("startTime").toString();
    		String endTime = map.get("endTime").toString();
    		datas = getDataByname(ncMethod,startTime,endTime);
    		//ncData中可能存在特殊字符，需转义
    		ncData = URLEncoder.encode(datas, "utf-8");
    		if(ncData.length()== 35) {
            	 return "--"+ncMethod+"无数据";
          }
    	}else {
    		//根据病案号传
    		String bah = map.get("bah").toString();
    		ncData = getDataBybah(ncMethod,bah);
    		if(ncData.length()== 35) {
    			Log.info(bah+"--"+ncMethod+"无数据");
             	 return "";
           }
    	}
    	
        //当前时间戳
        String ncTimestamp = DateUtil.currentTime();

        //计算随机值
        String ncNonce = MD5Util.md5(ncTimestamp);

        Map<String, String> param = new LinkedHashMap<String, String>(){
            {
                put("ncAppid", institutionInfo.get("ncAppid"));
                put("ncMethod", ncMethod);
                put("ncTimestamp", ncTimestamp);
                put("ncVersion", institutionInfo.get("ncVersion"));
                put("ncHistory", institutionInfo.get("ncHistory"));
                put("ncCancel", institutionInfo.get("ncCancel"));
                put("ncNonce", ncNonce);
                put("ncBranchID", institutionInfo.get("ncBranchID"));
            }
        };

        //计算签名
        StringBuilder encryption_str = new StringBuilder();
        for(Map.Entry<String, String> entry : param.entrySet()) {
            encryption_str.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        encryption_str.append("appsecret").append("=").append(institutionInfo.get("ncAppSecret"));
        String ncSign = MD5Util.md5(encryption_str.toString().toLowerCase());

        param.put("ncData", ncData);
        param.put("ncSign", ncSign);

        StringBuilder paramStr = new StringBuilder();
        for(Map.Entry<String, String> entry : param.entrySet()) {
            paramStr.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        String responseString = HttpUtil.doPost(DEFAULT_URL, paramStr.toString());
        Map<String,Object> insertMap = new HashMap<String, Object>();
        insertMap.put("ncMethod", ncMethod);
        if("1".equals(map.get("type"))) {
        	Map<String,Object> maps = JSON.parseObject(datas);
        	String lists = maps.get("dataList").toString();
        	List<Map<String, Object>> lista = toListMap(lists);
        	String zyhm = "";
        	for(int i = 0;i<lista.size();i++) {
        		String bah = lista.get(i).get("ncMedicalRecordNo").toString();
        		zyhm = zyhm + bah ;
        		if(i!=lista.size()-1) {
        			zyhm = zyhm +  ",";
        		}
        	}
        	insertMap.put("zyhm", zyhm);
        }else {
        	//bah情况主键
        	insertMap.put("zyhm", map.get("bah"));
        }
        insertMap.put("response", stringToUnicode(responseString));
        //插入log方法
        mainUtils.hisServiceImpl.insertSelectiveLog(insertMap);
        Log.info("返回结果："+responseString);
        return responseString;
    }
    
    /*
     * unicode编码
     */
    public static String stringToUnicode(String str) {
        char[] utfBytes = str.toCharArray();
        StringBuilder unicodeBytes = new StringBuilder();
        for (char utfByte : utfBytes) {
            String hexB = Integer.toHexString(utfByte);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes.append("\\u").append(hexB);
        }
        return unicodeBytes.toString();
    }
    
    //jsonString 转 listmap
    public  List<Map<String, Object>> toListMap(String json){
        List<Object> list =JSON.parseArray(json);
        List< Map<String,Object>> listw = new ArrayList<Map<String,Object>>();
        for (Object object : list){
            Map<String,Object> ageMap = new HashMap<String,Object>();
            Map <String,Object> ret = (Map<String, Object>) object;//取出list里面的值转为map
            listw.add(ret);
        }
        return listw;
         
    }

    public  String getDataFromFile(String ncMethod) throws UnsupportedEncodingException, FileNotFoundException {
        //封装ncData
        StringBuilder data = new StringBuilder();
        BufferedReader reader = new BufferedReader(new FileReader("templates/" + ncMethod +  ".json"));
        reader.lines().forEach(line -> data.append(line.trim()));
        //ncData中可能存在特殊字符，需转义
        return URLEncoder.encode(data.toString(), "utf-8");
    }
    
    public  String getDataByname(String methodName,String startTime,String endTime) throws UnsupportedEncodingException {
    	String viewName = METHOD_VIEWS.get(METHOD_NAMES.indexOf(methodName));
    	Log.info("--------------视图-->"+viewName+"------------------");
    	Log.info("--------------start-->"+startTime+"-end-----"+endTime);
    	Map<String,Object> map = new HashMap<String, Object>();
    	map.put("viewName", viewName);
    	map.put("startTime", startTime);
    	map.put("endTime", endTime);
    	map.put("type", "1");
        String data =mainUtils.hisServiceImpl.getData(map);
        return data;
    }
    
    public  String getDataBybah(String methodName,String bah) {
    	String viewName = METHOD_VIEWS.get(METHOD_NAMES.indexOf(methodName));
    	Log.info("--------------视图-->"+viewName+"------------------");
    	Log.info("--------------bah-->"+bah+"-end-----");
    	Map<String,Object> map = new HashMap<String, Object>();
    	map.put("viewName", viewName);
    	map.put("bah", bah);
    	map.put("type", "2");
        String data =mainUtils.hisServiceImpl.getData(map);
        Log.info("data--->"+data);
        try {
        	//ncData中可能存在特殊字符，需转义
			return URLEncoder.encode(data, "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}
    }
    
    @PostConstruct
    public void init() {    
    	mainUtils = this;
    }

    public  void AllMethod(String startTime,String endTime) throws FileNotFoundException, UnsupportedEncodingException {
    	Map<String,Object> map = new HashMap<String, Object>();
    	map.put("startTime", startTime);
    	map.put("endTime", endTime);
    	map.put("type", "1");
        for(String method : METHOD_NAMES) {
            upload(method,map);
        }
    }
    
    public  void AllMethodbybah(String bah) throws FileNotFoundException, UnsupportedEncodingException {
    	Map<String,Object> map = new HashMap<String, Object>();
    	map.put("type", "2");
    	map.put("bah", bah);
        for(String method : METHOD_NAMES) {
            upload(method,map);
        }
    }

    public  void main(String startTime,String endTime) throws IOException {
        //所有接口根据时间查询
        AllMethod(startTime,endTime);
    }
    
    public  void getBybah(String bah) throws IOException {
        //所有接口根据病案号查询
        AllMethodbybah(bah);
    }
}
